import Taro, { Component } from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import classNames from 'classnames'
import { DNavBar, DAtInpute } from '@/components'
import { AtForm, AtButton, AtIcon } from 'taro-ui'
import http from '@/api'
import md5 from 'js-md5'
import sdk from '@/common/sdk'
import './editphone.scss'
import EditPasswordComponent from '../editPassword/editPassword'
let _timenumber = ''
export default class EditphoneBox extends Component {
    constructor(props) {
        super(props)
        this.state = {
            title: '手机号码',
            isShow: false,
            numberInfo: 60,
            userInfo: {
                telphone: '13600053041',
                firstPhone: '',
                firstCode: '',
                password: '',
                newphone: '',
                secondCode: '',
                firstPassword: ''
            },
            tips: '请输入手机号码',
            tips2: '',
            type: 'telphone',
            statusPass: false,
            firstCode: '',
            secondCode: ''
        }
    }

    componentWillMount() {
        let { telphone, type = 'telphone' } = this.$router.params
        let { title, tips } = this.state
        if (type === 'telphone') {
            title = '修改手机号码'
            tips = ''
        } else if (type === 'password') {
            title = '找回密码'
        }
        this.setState({
            userInfo: {
                ...this.state.userInfo,
                telphone,
                firstPhone: telphone
            },
            type,
            tips,
            title
        }, () => {
            sdk.setTitleInfo(this.state.title)
        })
    }

    getNumberCode(key) {
        let { numberInfo, userInfo, firstCode, secondCode, type } = this.state

        if (numberInfo !== 60) {
            return
            //  Taro.showToast({
            //     title: "验证码已发送！",
            //     icon: "none"
            // })
        } else if (!(/^1[3456789]\d{9}$/.test(userInfo.firstPhone))) {
            this.setState({
                tips2: '请输入正确的手机号码~'
            })
            return Taro.showToast({
                title: "手机号码格式错误",
                icon: "none"
            })
        } else {
            Taro.showToast({
                title: '验证码已发送',
                duration: 800
            })
            if (type === 'password') {
                this.setState({
                    tips: `您的手机号${userInfo.firstPhone}会收到一条含有6位数字验证码的短信`,
                    tips2: ''
                })
            }

            http.getUserCode({
                mobile: userInfo.firstPhone,
                type: '3'
            }).then(res => {
                if (key === 'firstCode') {
                    firstCode = res
                } else if (key === 'secondCode') {
                    secondCode = res
                }
                this.setState({
                    userInfo: Object.assign(this.state.userInfo, { [key]: res }),
                    firstCode,
                    secondCode,
                    res
                })
            })
        }
        _timenumber = setInterval(() => {
            if (numberInfo === 0) {
                numberInfo = 60
                clearInterval(_timenumber)
            } else {
                numberInfo--
            }
            this.setState({
                numberInfo
            })
        }, 1000)
    }
    //下一步
    NextStep() {
        let { userInfo, type, firstCode } = this.state
             let isNum = userInfo['firstCode'].length
        if (type === 'telphone') {
            let _userinfo = ['firstCode', 'firstPhone', 'firstPassword']
            let status = true
            _userinfo.map(item => {
                if (!userInfo[item]) {
                    status = false
                }
            })
            if (!status) {
                return Taro.showToast({
                    title: '请您完善填写信息！',
                    icon: "none",
                    duration: 800
                })
            }
			
            if (!userInfo['firstCode']||userInfo['firstCode'].length!==6) {
                return this.setState({
                    tips2: '您输入的验证码有误，请核对后输入~'
                })
                // Taro.showToast({
                //     title: '验证码填写有误！',
                //     icon: "none",
                //     duration: 800
                // })
            }
			
            http.getPasswordRight({ oldPassword:!this.$router.params.md5?md5(userInfo.firstPassword):userInfo.firstPassword  })
                .then(res => {
                    if (res) {
                        clearInterval(_timenumber)
                        this.setState({
                            numberInfo: 60,
                            isShow: true
                        },()=>{
							http.setUserPhone({ code: userInfo['firstCode'],phone:userinfo.phone })
							    .then(res => {
							        if (res) {
							            clearInterval(_timenumber)
							            this.setState({
							                numberInfo: 60,
							                isShow: true
							            })
							        } else {
							            return Taro.showToast({
							                title: '密码输入错误！',
							                icon: 'none',
							                duration: 800
							            })
							        }
							    })
						})
                    } else {
                        return Taro.showToast({
                            title: '密码输入错误！',
                            icon: 'none',
                            duration: 800
                        })
                    }
                })
        } else if (type === 'password') {
		
            let _userinfo = ['firstCode', 'firstPhone']
            let status = true
            _userinfo.map(item => {
                if (!userInfo[item]) {
                    status = false
                }
            })
            if (!status) {
                return Taro.showToast({
                    title: '请您完善填写信息！',
                    icon: "none"
                })
            }
			debugger
            if (!userInfo['firstCode']||userInfo['firstCode'].length!==6) {
                return this.setState({
                    tips2: '您输入的验证码有误，请核对后输入~'
                })
                // Taro.showToast({
                //     title: '验证码填写有误！',
                //     icon: "none",
                //     duration: 800
                // })
            }
			
            clearInterval(_timenumber)
			// http.checkCode({code:userInfo['firstCode'],mobile:userInfo['firstPhone'],type:'3'}).then(res=>{
				
			// })
            // this.setState({
            //     numberInfo: 60
            // }, () => {
            //     Taro.navigateTo({
            //         url: `/pages/editpassword/editpassword?telphone=${userInfo.firstPhone}&type=password`
            //     })
            // });
        }
    }
    //返回上一步
    onClickLeftIcon() {
        let { isShow } = this.state
        if (isShow) {
            clearInterval(_timenumber)
            this.setState({
                isShow: false,
                numberInfo: 60
            });
        } else {
            Taro.navigateBack({ delta: 1 })
        }

    }

    onSubmit() {
        let _userinfo = ['newphone', 'secondCode']
        let status = true
        let { userInfo, secondCode } = this.state
        _userinfo.map(item => {
            if (!userInfo[item]) {
                status = false
            }
        })
        if (!status) {
            return Taro.showToast({
                title: '请您完善填写信息！',
                icon: "none"
            })
        }

        if (secondCode &&secondCode.length!==6) {
            return Taro.showToast({
                title: '验证码填写有误！',
                icon: "none",
                duration: 800
            })
        }
        http.setUserPhone({ phone: userInfo.newphone, code: secondCode }).then(res => {
            Taro.showToast({
                title: '已修改手机',
                duration: 800,
                mask: true
            }).then(() => {
                setTimeout(() => {
                    Taro.navigateBack({
                        delta: 1
                    })
                }, 1000)
            })
        })
    }

    bindCarform(key, value) {
        if (key) {
            this.setState({
                userInfo: Object.assign(this.state.userInfo, { [key]: value })
            })
        }
    }

    onPasswordHandle() {
        let { statusPass } = this.state
        statusPass = !statusPass
        this.setState({
            statusPass
        })
    }

    render() {
        const {
            userInfo,
            isShow,
            numberInfo,
            title,
            type,
            statusPass,
            tips,
            tips2
        } = this.state
       console.log("sds",isShow,type)
        const _bindCarform = function (value) {
            this.bindCarform(arguments[arguments.length - 1].bind, value)
        }
		
        return (
		
            <View className='b_editphone'>
			
                <DNavBar title={title} status={isShow} onClickLeftIcon={this.onClickLeftIcon.bind(this)}></DNavBar>
                {tips && <View className='b_editphone__tips'>{tips}</View>}
                <View className={classNames(isShow ? '' : 'showbox', 'b_editphone__box', 'b_editphone__box_oldpassword')}>
                    <View className='b_editphone__form'>
                        <AtForm>
                            {/* {
                                userInfo.telphone && <View className="b_editphone__form_row">
                                    <Text>{userInfo.telphone}</Text>
                                </View>
                            } */}
                            <View className="b_editphone__form_row b_editphone__form_code">
                                <DAtInpute title='手机号码' bind="firstPhone" onChange={_bindCarform.bind(this)} value={userInfo.firstPhone} type='phone' placeholder='请输入手机号码'></DAtInpute>
                                <AtButton className={classNames(numberInfo !== 60 ? 'disabled' : '', 'item_btn')} onClick={this.getNumberCode.bind(this, 'firstCode')}>{numberInfo !== 60 ? numberInfo + 's' : '获取验证码'}</AtButton>
                            </View>
                            <View className="b_editphone__form_row">
                                <DAtInpute type='number' title='验证码' bind='firstCode' onChange={_bindCarform.bind(this)} value={userInfo.firstCode} placeholder='请输入验证码'></DAtInpute>
                            </View>
                            {
                                type === 'telphone' && <View className="b_editphone__form_row">
                                    <DAtInpute maxLength={20} type={statusPass ? 'text' : 'password'} title='密码' bind='firstPassword' onChange={_bindCarform.bind(this)} value={userInfo.firstPassword} placeholder='请输入密码'></DAtInpute>
                                    <AtIcon className={classNames(statusPass ? '' : 'b_editphone__form_row-line')} value='eye' size='24' color='#666' onClick={this.onPasswordHandle.bind(this)}></AtIcon>
                                </View>
                            }
							{
							    type === 'password'&&<EditPasswordComponent {...userInfo} NextStep={this.NextStep.bind(this)} />
							}
                        </AtForm>
                    </View>
                    <View className="b_editphone__tips2">{tips2}</View>
                    <View className='b_editphone__footer'>
                        {type==='telphone'&&<AtButton className='item_btn' onClick={this.NextStep.bind(this)}>下一步</AtButton>}
                    </View>
                </View>
                <View className={classNames(isShow ? 'showbox' : '', 'b_editphone__box', 'b_editphone__box_newpassword')}>
                    <View className='b_editphone__form '>
                        <AtForm>
                            <DAtInpute title='手机号码' bind='newphone' onChange={_bindCarform.bind(this)} value={userInfo.newphone} type='phone' placeholder='请输入新的手机号码'></DAtInpute>
                            <View className='b_editphone__form_code'>
                                <DAtInpute type='number' title='验证码' bind='secondCode' onChange={_bindCarform.bind(this)} value={userInfo.secondCode} placeholder='请输入验证码'></DAtInpute>
                                <AtButton className={classNames(numberInfo !== 60 ? 'disabled' : '', 'item_btn')} onClick={this.getNumberCode.bind(this, 'secondCode')}>{numberInfo !== 60 ? numberInfo + 's' : '获取验证码'}</AtButton>
                            </View>
                        </AtForm>
                    </View>
                    <View className='b_editphone__footer'>
                        <AtButton className='item_btn' onClick={this.onSubmit.bind(this)}>完成</AtButton>
                    </View>
                </View>
            </View>
        )
    }
}